package cn.cfoodc.sharding.controller;

import cn.cfoodc.sharding.domain.En;
import cn.cfoodc.sharding.domain.Encryptor;
import cn.cfoodc.sharding.service.EnService;
import cn.cfoodc.sharding.service.EncryptorService;
import org.apache.shardingsphere.sharding.algorithm.keygen.SnowflakeKeyGenerateAlgorithm;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Encryptor类的name、pwd、
 */
@RestController
public class DemoEnContorller {
    private EnService enService;
    private SnowflakeKeyGenerateAlgorithm NEXT_ID ;
    @Autowired
    public DemoEnContorller(EnService enService , SnowflakeKeyGenerateAlgorithm snowflakeKeyGenerateAlgorithm ){
        this.enService=enService;
        this.NEXT_ID=snowflakeKeyGenerateAlgorithm;
    }

    //添加一条记录，按照id % 3 落入到对应库.表中，会发起一条sql
    @PostMapping("/inserEnAndArgs")
    @Transactional(rollbackFor = { Exception.class })
    @ShardingTransactionType(TransactionType.XA)// 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE，这里只引入了XA
    public int insert(@ModelAttribute En en){
        En e = new En();
        e.setId((Long) NEXT_ID.generateKey());
        e.setName(en.getName());
        e.setPrivateKetCipher(en.getPrivateKetCipher());
        e.setPublicKetCipher(en.getPublicKetCipher());
        return enService.insert(e);
    }


    @GetMapping("/selectEnAll")
    public List<En> selectAll(){
        return enService.selectAll();
    }

}
